#include "dialog_stu.h"
#include "ui_dialog_stu.h"
#include "stusql.h"
#include <QMessageBox>
Dialog_AddStu::Dialog_AddStu(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog_AddStu)
{
    ui->setupUi(this);
}

Dialog_AddStu::~Dialog_AddStu()
{
    delete ui;
}

void Dialog_AddStu::setType(bool isAdd, StuInfo info)
{
    m_isAdd=isAdd;
    m_info=info;
    ui->le_name->setText(info.sname);
    ui->sb_age->setValue(info.age);
    ui->le_class->setText(QString::number(info.sclass));
    ui->le_grade->setText(QString::number(info.grade));
    ui->le_phone->setText(info.phone);
}
void Dialog_AddStu::on_pb_save_clicked()
{
    StuInfo info=m_info;
    auto ptr = stuSql::getInstance();

    // 获取用户输入的信息
    info.sname = ui->le_name->text();
    info.age = ui->sb_age->value();
    info.sclass = ui->le_class->text().toUInt();
    info.grade = ui->le_grade->text().toUInt();
    info.phone = ui->le_phone->text();

    if(m_isAdd){
        // 随机生成学号
        int currentCount = ptr->getStuCnt();
        // 设置学号为51开头，并根据年级动态生成后缀
        QString sidPrefix = QString("5120%1").arg(26 - info.grade, 2, 10, QChar('0')); // 例如：一年级 -> 512025
        info.sid = QString("%1%2").arg(sidPrefix).arg(currentCount + 1, 3, 10, QChar('0')); // 学号后三位是学生总数加1，不足三位补0
        if (ptr->addStu(info)) {
            QMessageBox::information(nullptr, "信息", QString("该学生学号为 %1，学生信息添加成功！").arg(info.sid));
        } else {
            QMessageBox::critical(nullptr, "错误", "添加学生信息失败！");
        }
    }
    else{
        if (ptr->updateStu(info)) {
            QMessageBox::information(nullptr, "信息", QString("该学生信息修改成功！"));
        } else {
            QMessageBox::critical(nullptr, "错误", "修改学生信息失败！");
        }
    }
    this->hide();
}

void Dialog_AddStu::on_pb_cel_clicked()
{
    this->hide();
}

